package com.hugang.threadcreate;

import java.util.concurrent.*;

/**
 * 创建线程的方式四：使用线程池   --- JDK5 新增
 *
 * 好处：
 *  1、提高响应速度（减少了创建新线程的时间）
 *  2、降低资源的消耗（重复利用线程池中的线程，不需要每次都创建）
 *  3、便于线程管理：
 *      corePoolSize: 核心池的大小
 *      maximumPoolSize: 最大线程数
 *      keepAliveTime: 线程没有任务时最多保持多长时间后会终止
 *
 * @author hg
 * @date 2020/6/16 20:02
 */
public class ThreadPool {

    public static void main(String[] args) {
        //1、提供指定线程数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service = (ThreadPoolExecutor) executorService;
        service.setCorePoolSize(15);
//        service.setKeepAliveTime();
//        ExecutorService executorService = executorService = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

        //2、执行指定的线程的操作，需要提供实现Runnable接口或Callable接口实现类的对象
        //适合使用于Runnable
//        executorService.execute(new NumberThread());
//        executorService.execute(new NumberThread1());

        NumberThread2 numberThread2 = new NumberThread2();
        //适合使用于Callable
        Future future = executorService.submit(numberThread2);

        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //3、使用完需要关闭线程池
        executorService.shutdown();
    }
}

class NumberThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread1 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 1) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread2 implements Callable {

    private int sum;

    @Override
    public Object call() throws Exception {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 1) {
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
